#include "..\..\include\guiappedit.h"
#include "..\..\include\guiappwindow.h"

GUIAppEdit::GUIAppEdit(int _id, float x, float y, float w, hgeFont* fnt, char* str) {
	bStatic = false;
	bVisible = true;
	bEnabled = true;
	id=_id;

	m_Font = fnt;
	m_Focus = false;

	m_Time = 0;
	m_Blink = 0;

	strcpy(m_Text,str);
	m_Pos = strlen(m_Text);

	rect.Set(x-2, y-2, x+w+4, y+fnt->GetHeight()*fnt->GetScale()+4);
	frameColor = ARGB(0xff,0xff,0xff,0xff);
	textColor = ARGB(0xff,0xff,0xff,0xff);
}

bool GUIAppEdit::KeyClick(int key, int chr) {
	if ( m_Focus ) {
		int i, len = strlen(m_Text);
		
		switch (key) {
		case HGEK_ENTER:
			parentwin->OnEvent(id);
			m_Focus = false;
			break;
		case HGEK_TAB:
			parentwin->OnEvent(id);
			m_Focus = false;
			break;
		case HGEK_LEFT:
			if (m_Pos > 0) {
				m_Pos--;
			}
			break;
		case HGEK_RIGHT:
			if (m_Pos < (int)strlen(m_Text)) {
				m_Pos++;
			}
			break;
		case HGEK_DELETE:
			for (i=m_Pos; i<len; i++) {
				m_Text[i] = m_Text[i+1];
			}
			break;
		case HGEK_BACKSPACE:
			if (m_Pos == 0) {
				break;
			}
			for (i=m_Pos; i<len+1; i++) {
				m_Text[i-1] = m_Text[i];
			}
			m_Pos--;
			break;
		default:
			{
				if (chr == 0) {
					break;
				}
				
				char tmp[64];
				strcpy(tmp, m_Text);
				
				for (i=len; i>m_Pos && i>0; i--) {
					m_Text[i] = m_Text[i-1];
				}

				m_Text[m_Pos] = chr;
				m_Text[len+1] = 0;
				m_Pos++;
				
				if (m_Font->GetStringWidth(m_Text) > rect.x2 - rect.x1) {
					strcpy(m_Text, tmp);
					m_Pos--;
				}
			}
			break;
		};
		
		// keep caret from vanishing
		m_Blink = true; 
		m_Time = 0;
	}
	return false;
}

void GUIAppEdit::Selected(bool bDown) {
	m_Focus = bDown;
	GUIAppObject::Selected(bDown);
}

void GUIAppEdit::Update(float dt) {
	if (m_Focus) {
		m_Time += dt;
		if (m_Time > 0.3) {
			m_Time = 0;
			m_Blink = !m_Blink;
		}
	}
}

void GUIAppEdit::Render() {
	hge->Gfx_RenderLine(rect.x1, rect.y1, rect.x2, rect.y1, frameColor);
	hge->Gfx_RenderLine(rect.x2, rect.y1, rect.x2, rect.y2, frameColor);
	hge->Gfx_RenderLine(rect.x2, rect.y2, rect.x1, rect.y2, frameColor);
	hge->Gfx_RenderLine(rect.x1, rect.y2, rect.x1, rect.y1, frameColor);

	m_Font->SetColor(textColor);
	m_Font->Render(rect.x1 + 2, rect.y1 + 2, HGETEXT_LEFT, m_Text);

	if (m_Focus && m_Blink) {
		char tmp[64]; 
		strncpy(tmp, m_Text, m_Pos);
		tmp[m_Pos] = 0;

		float p = m_Font->GetStringWidth(tmp);
		hge->Gfx_RenderLine(rect.x1 + 2 + p, rect.y1 + 2, rect.x1 + 2 + p, rect.y2 - 2, textColor);
	}
}

void GUIAppEdit::Move(float dx, float dy) {
	rect.Set(rect.x1-dx,rect.y1-dy,rect.x2-dx,rect.y2-dy);
}